package zb.demo.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Component;
import zb.blog.base.util.PropertiesUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 画制定logo和制定描述的二维码
 *
 * @author songyz
 */
@Component
public class QrcodeUtil {
    private static final int QRCOLOR = 0xFF000000; // 默认是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色
    private static final int WIDTH = 400; // 二维码宽
    private static final int HEIGHT = 400; // 二维码高
    public static final String PATH_LOC_TEM = PropertiesUtil.getPropValue("demo.fileinputupload.path");

    /**
     * 生成二维码电子名片
     *
     * @param logoFile logo图片相对路径
     * @param content  二维码内容
     * @return 返回二维码路径
     */
    public static String getQrcode(String logoFile, String content) {
        try {
            Map<EncodeHintType, Object> map = new HashMap<>();
            // L级：约可纠错7%的数据码字
            // M级：约可纠错15%的数据码字
            // Q级：约可纠错25%的数据码字
            // H级：约可纠错30%的数据码字
            // 纠错能力越高，存储的数据就越少
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
            map.put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
            map.put(EncodeHintType.MARGIN, 0);
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix bm = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, map);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            //如果上传了logo
            if (logoFile != null) {
                BufferedImage logo = ImageIO.read(new File(logoFile));
                //将上传的log卡U你高设置为80px
                Image logoImg = logo.getScaledInstance(80, 80, Image.SCALE_DEFAULT);
                BufferedImage logo_ = new BufferedImage(logoImg.getWidth(null), logoImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
                int logo_W = logo_.getWidth();
                int logo_H = logo_.getHeight();
                int QrcodeW = image.getWidth();
                int QrcodeH = image.getHeight();
                int x = QrcodeW / 2 - logo_W / 2;
                int y = QrcodeH / 2 - logo_H / 2;
                Graphics2D g = image.createGraphics();
                g.setColor(Color.WHITE);
                g.drawRoundRect(x, y, 90, 90, 8, 8);
                g.fillRoundRect(x, y, 90, 90, 8, 8);
                g.drawImage(logo, x + 5, y + 5, 80, 80, null);
                g.dispose();
                logo.flush();
            }
            image.flush();
            String relativePath = UUID.randomUUID() + ".png";
            String savePath = PATH_LOC_TEM + relativePath;
            ImageIO.write(image, "png", new File(savePath));
            return relativePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String logoFile = "E:\\head.jpg";
        String content =
                "BEGIN:VCARD\n" +
                        "VERSION:3.0\n" +
                        "FN:zhangbin\n" +
                        "TEL;CELL;VOICE:147878*****\n" +
                        "TEL;WORK;VOICE:147878*****\n" +
                        "EMAIL;PREF;INTERNET:405848266@qq.com\n" +
                        "URL:https://www.zhangbin.xin\n" +
                        "ADR;WORK;POSTAL:云南省昆明市西山区广福路要龙大厦9楼;爆笑江湖文化传播有效公司\n" +
                        "ROLE:研发部\n" +
                        "TITLE:JAVA开发\n" +
                        "END:VCARD";
        getQrcode(logoFile, content);
    }

}